package com.travelsmart.client.apresentacao.model;

import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.travelsmart.client.apresentacao.controller.Observable;
import com.travelsmart.client.apresentacao.i18n.I18nMessages;
import com.travelsmart.client.apresentacao.model.SmartHotelModel.LOAD_STATUS;
import com.travelsmart.client.bean.to.FilterPesquisaHotel;
import com.travelsmart.client.bean.to.HotelTO;
import com.travelsmart.client.bean.to.ParametroOrdenacao;
import com.travelsmart.client.control.HotelSmartServiceAsync;

public class ListHotelModel extends Observable<List<HotelTO>> {
	private List<HotelTO> hoteis;
	
	public void pesquisaListHotel(final FilterPesquisaHotel filter) {
		// INICIO - EXERC. 3
		SmartHotelModel.instance.getFilterPesquisaHotelModel().setFilterPesquisaHotel(filter);
		SmartHotelModel.instance.getLoadModel().setLoad(LOAD_STATUS.LOADING);
		// FIM - EXERC. 3
		HotelSmartServiceAsync.service.listaHotel(filter,
				new AsyncCallback<List<HotelTO>>() {
					public void onFailure(Throwable caught) {
						SmartHotelModel.instance.getLoadModel().setLoad(LOAD_STATUS.DONE);
						SmartHotelModel.instance.getErroHotelModel().setErro(caught);
					}

					public void onSuccess(List<HotelTO> hoteis) {
						SmartHotelModel.instance.getLoadModel().setLoad(LOAD_STATUS.DONE);
						if (hoteis == null || hoteis.isEmpty()) {
							SmartHotelModel.instance.getErroHotelModel().setErro(new RuntimeException(
									I18nMessages.INSTANCE
											.MSG_HOTEIS_INDISPONIVEIS()));
						} else {
							setHoteis(hoteis);
						}

					}
				});
	}

	public void ordenaListHotel(final ParametroOrdenacao param) {
		// INICIO - EXERC. 3
		SmartHotelModel.instance.getLoadModel().setLoad(LOAD_STATUS.LOADING);
		HotelSmartServiceAsync.service.sortList(hoteis, 
				param.isAscendente(), param.getColuna(), 
				new AsyncCallback<List<HotelTO>>() {
					@Override
					public void onSuccess(List<HotelTO> result) {
						SmartHotelModel.instance.getLoadModel().setLoad(LOAD_STATUS.DONE);
						setHoteis(result);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						SmartHotelModel.instance.getLoadModel().setLoad(LOAD_STATUS.DONE);
						SmartHotelModel.instance.getErroHotelModel().setErro(caught);
							
					}
				});
		//FIM - EXERC. 3
	}

	private void setHoteis(List<HotelTO> hoteis) {
		this.hoteis = hoteis;
		super.setChanged();
		super.notifyObservers(hoteis);
	}

}
